// ==UserScript==
// @name         shanbay Auto-Click Script
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Automatically interact with specified elements on web pages with adjustable wait time
// @author       You
// @match        *://dictionary.cambridge.org/*
// @match        *://dict.youdao.com/*
// @match        https://web.shanbay.com/wordsweb/#/study?type=book
// @match        https://web.shanbay.com/wordsweb/#/study?type=collection
// @match        https://web.shanbay.com/wordsweb/#/study/done?type=collection&success=false
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    var isPaused = false;
    var settings = initializeSettings();
    var pauseResumeButton = createPauseResumeButton();


    function initializeSettings() {
        return {
            clickElements: [
                "#root > div > div > div > div > div.StudyPage_nextBtn__1ygGn",
                "#root > div > div > div > div > div > div > div.index_btnBox__pXO_l > div.index_option__1CVr2.index_green__2lFgU > div.index_content__1XOlo",
                // "#root > div > div > div > div > div > div > div.index_btnBox__pXO_l > div.index_option__1CVr2.index_red__VSPTN", // Not Recognize
                // "#root > div > div > div > div > div:nth-child(1) > div > div > div > div.row.mb10 > div.span9 > div > div > div.index_flex__ka9KD > div.index_titleBox__2HKmC > p > span",
                "#root > div > div.Layout_main__2_zw8 > div > header > div:nth-child(2) > button",
            ],
            elementsToRemove: [
                'div > div > div > div:nth-child(1) > div.span9',
                '#root > div > div > div > div > div:nth-child(1) > div > div > div > div.row.mb10 > div.span9 > div > div > div.index_hidden__31I-6.index_display__185l5 > div > div > div.index_title__K3JZX > p',
                'div > div > div > div:nth-child(3) > div.span9 > div > div:nth-child(2) > div:nth-child(1) > div > div.BayTrans_exampleBox__3CsaJ > p', // 撤销
                '#root > div > div > div > div > div:nth-child(1) > div > div > div > div:nth-child(1) > div.span9', // 撤销
                '#root > div > nav.Nav_nav__3kyeO', // 扇贝
                '#root > div > nav.SubNav_subnav__1HR8R', // 学习单词
            ],
            elementsToMakeTransparent: [
                '#root > div > div > div > div > div:nth-child(1) > div > div > div > div.row.mb10 > div.span9 > div > div > div.index_hidden__31I-6.index_display__185l5 > div',
                '#root > div > div > div > div > div:nth-child(1) > div > div > div > div.row.mb10 > div.span9 > div > div > div.index_hidden__31I-6.index_display__185l5 > div',
            ],
            elementsToChangeBackgroundColor: [
                '#root > div > div > div > div > div:nth-child(1) > div > div > div > div.row.mb10 > div.span9 > div > div > div.index_hidden__31I-6.index_display__185l5 > div > div'
                // 在这里添加其他需要改变背景颜色的元素选择器
            ],
            waitTime: 1000,
            backgroundColor: 'rgba(0,0,0,.7)',
        };
    }


    function createPauseResumeButton() {
        var button = document.createElement('button');
        button.textContent = 'Running';
        styleButton(button, 'green');
        button.addEventListener('click', togglePauseResume);
        document.body.appendChild(button);
        return button;
    }


    function styleButton(button, color) {
        button.style = `border-radius: 50%; width: 50px; height: 50px;
                        background-color: ${color}; position: fixed; top: 20px;
                        right: 20px; z-index: 9999; color: white; border: none;
                        cursor: pointer;`;
    }


      // Function to dynamically adjust button size based on content
      function adjustButtonSize() {
          var textLength = pauseResumeButton.textContent.length;
          var buttonSize = textLength * 10; // Adjust the multiplier as needed

          pauseResumeButton.style.width = buttonSize + 'px';
          pauseResumeButton.style.height = buttonSize + 'px';
      }


    function removeElements(selectors) {
        selectors.forEach(function(selector) {
            var element = document.querySelector(selector);
            if (element) element.remove();
        });
    }


    function determineWaitTime() {
        var nextButtonElement = document.querySelector("#root > div > div > div > div > div.StudyPage_nextBtn__1ygGn"); // wait for 5s on page having next button
        return nextButtonElement ? 5000 : 1000;
    }


    function copyElementAfterTarget() {
        var elementToCopy = document.querySelector('div.index_content__C4Uws');
        var targetElement = document.querySelector('#root > div > div > div > div > div:nth-child(1) > div > div > div > div:nth-child(3)');

        if (elementToCopy && targetElement) {
            var copiedElement = elementToCopy.cloneNode(true);
            targetElement.parentNode.insertBefore(copiedElement, targetElement.nextSibling);
        }
    }


    function togglePauseResume() {
        // Toggle the pause state
        isPaused = !isPaused;

        // Update the button appearance based on the new state
        styleButton(pauseResumeButton, isPaused ? 'red' : 'green');
        pauseResumeButton.textContent = isPaused ? 'Resume' : 'Pause';

        if (isPaused) {
            // If the script is now paused, clear any pending timeout
            if (clickTimeout) {
                clearTimeout(clickTimeout);
                clickTimeout = null; // Ensure we don't try to clear it again
            }
        } else {
            // If the script was paused and is now resumed, restart the clicking process
            clickTimeout = setTimeout(clickElements, settings.waitTime);
        }
    }


  function clickElements() {
      for (var i = 0; i < settings.clickElements.length; i++) {
          var selector = settings.clickElements[i];
          var element = document.querySelector(selector);
          if (element && !isPaused) {
              removeElements(settings.elementsToRemove);

              // The wait time should be determined before setting the timeout.
              settings.waitTime = determineWaitTime();

              // Set a timeout to perform the click action after the determined wait time.
              setTimeout((function(element) {
                  return function() {
                      element.click();
                      copyElementAfterTarget();
                  };
              })(element), settings.waitTime);

              // Break out of the loop after setting the timeout.
              break;
          }
      }


    // If not paused, set a timeout to call clickElements again.
    // This timeout should be set to call clickElements after the click has occurred,
    // so it needs to include the wait time for the click plus an additional delay.
    if (!isPaused) {
        setTimeout(clickElements, settings.waitTime);
    }
  }
    // Call the function to adjust button size initially
    adjustButtonSize();

    clickElements();
})();
